package server

import (
	"fmt"

	"github.com/TarsCloud/TarsGo/tars"
	"github.com/TarsCloud/TarsGo/tars/util/conf"
	hypernexusclient "github.com/wzh200x/hyperNexus/hyperNexusClient"
	"github.com/wzh200x/hyperNexus/hyperNexusProtocol/interfaceServerProtocol"
	"github.com/wzh200x/interfaceServer/platform"
	// 导入Web服务器协议包
)

// InterfaceServer 定义Web服务器结构体
type InterfaceServer struct {
	// 可以在这里添加需要的服务器组件
	DbAgentServerClient *hypernexusclient.DbAgentServerClient
	CacheServerClient   *hypernexusclient.CacheServerClient
	PlatformHelper      *platform.PlatformHelper
}

// ServerApp 是全局服务器实例
var ServerApp = &InterfaceServer{}

// Init 初始化服务器
func (is *InterfaceServer) Init(comm *tars.Communicator, sConf *conf.Conf) error {
	// 初始化tars
	is.RegisterTarsObj()
	// 初始化DbAgentServerClient
	is.DbAgentServerClient = hypernexusclient.NewDbAgentServerClient()
	err := is.DbAgentServerClient.Init(comm)
	if err != nil {
		tars.GetLogger("").Errorf("Failed to initialize DbAgentServerClient: %v", err)
		return err
	}

	// 初始化CacheServerClient
	is.CacheServerClient = hypernexusclient.NewCacheServerClient()
	err = is.CacheServerClient.Init(comm)
	if err != nil {
		tars.GetLogger("").Errorf("Failed to initialize CacheServerClient: %v", err)
		return err
	}
	tars.GetLogger("").Infof("InterfaceServer initialized successfully")

	// 初始化平台助手
	is.PlatformHelper = platform.NewPlatformHelper()
	is.PlatformHelper.Init()

	return nil
}

// InitFinish 完成初始化后的操作
func (is *InterfaceServer) InitFinish() error {
	return nil
}

// Info 返回服务器信息
func (is *InterfaceServer) Info() string {
	return fmt.Sprintf(`server: %s version: %s`, "interfaceServer", "0.0.1")
}

// Name 返回服务器名称
func (is *InterfaceServer) Name() string {
	return "interfaceServer"
}

func (is *InterfaceServer) Stop() error {
	return nil
}

// RegisterTarsObj 注册Tars对象
func (is *InterfaceServer) RegisterTarsObj() {
	// Get server config
	cfg := tars.GetServerConfig()
	// // New servant imp
	imp := new(interfaceServerOperateImp)
	app := new(interfaceServerProtocol.InterfaceServer)
	// Register Servant
	app.AddServantWithContext(imp, cfg.App+"."+cfg.Server+".InterfaceServerOperateObj")
}
